//
//  SleepViewController.m
//  Light
//
//  Created by 骁唐 on 15/8/27.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//

#import "SleepViewController.h"
#import "AppDelegate.h"

@interface SleepViewController ()<UIApplicationDelegate,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xbtn;
@property (weak, nonatomic) IBOutlet UIView *slideView;
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImage;
@property (weak, nonatomic) IBOutlet UIImageView *btnImage;
@property (weak, nonatomic) IBOutlet UILabel *promptLabel;
@property (weak, nonatomic) IBOutlet UILabel *onLabel;
@property (weak, nonatomic) IBOutlet UIImageView *backGround;


@property (nonatomic, strong) UISwipeGestureRecognizer *leftSwipeGestureRecognizer;
@property (nonatomic, strong) UISwipeGestureRecognizer *rightSwipeGestureRecognizer;

@end

@implementation SleepViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    UserConfig * config = [UserConfig sharingUserConfig];
    delegate.sleepImprove = [config isSleepImprove];
    if (delegate.sleepImprove) {
        TJJLog(@"已经开启");
        self.xbtn.constant = self.slideView.frame.size.width/2;
        self.backgroundImage.image = [UIImage imageNamed:@"sleep - backgroundOn"];
        [self.view layoutIfNeeded];
    }else
    {
        self.xbtn.constant = 0;
        self.backgroundImage.image = [UIImage imageNamed:@"sleep - background"];
        [self.view layoutIfNeeded];
    }

    //开启睡眠改善功能 文案设置
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:MESSAGE_SLEEPING];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:10];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[MESSAGE_SLEEPING length])];
    [_promptLabel setAttributedText:attributedString];
    [_promptLabel sizeToFit];
    _onLabel.alpha = 0.6;
    
    //传值
    _writeCharacteristic = delegate.writeCharacteristic;
    _myPeripheral = delegate.peripheral;
    
    
    self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
    self.rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
    self.leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    self.rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.slideView addGestureRecognizer:self.leftSwipeGestureRecognizer];
    [self.slideView addGestureRecognizer:self.rightSwipeGestureRecognizer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return  YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark -
#pragma mark 关闭弹窗One
- (void)closeAlertViewOne
{
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    [delegate.alertAutoOne dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark -
#pragma mark 导航返回
- (IBAction)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark 关闭睡眠改善按钮，功能代开睡眠改善
- (IBAction)offClick {
    [UIView animateWithDuration:0.3 animations:^{
        self.xbtn.constant = self.slideView.frame.size.width/2;
        self.backgroundImage.image = [UIImage imageNamed:@"sleep - backgroundOn"];
        [self.view layoutIfNeeded];
    }];
    //开启睡眠改善
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_IMPROVESTART];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [self.myPeripheral writeValue:data
                    forCharacteristic:delegate.writeCharacteristic
                                 type:CBCharacteristicWriteWithResponse];
    }
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(sleepGaishan) userInfo:nil repeats:NO];
}
#pragma mark -
#pragma mark 打开睡眠改善按钮，功能关闭睡眠改善
- (IBAction)onClick {
    [UIView animateWithDuration:0.3 animations:^{
        self.xbtn.constant = 0;
        self.backgroundImage.image = [UIImage imageNamed:@"sleep - background"];
        [self.view layoutIfNeeded];
    }];
    
    //关闭睡眠改善
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_IMPROVEEND];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [self.myPeripheral writeValue:data
                    forCharacteristic:delegate.writeCharacteristic
                                 type:CBCharacteristicWriteWithResponse];
    }
    //3秒之后，检测睡眠改善是否关闭
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(sleepGaishan) userInfo:nil repeats:NO];

}

#pragma mark -
#pragma mark 睡眠改善是否开启
- (void)sleepGaishan
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    UserConfig * config = [UserConfig sharingUserConfig];
    delegate.sleepImprove = [config isSleepImprove];
    if (delegate.sleepImprove) {
        delegate.alertAutoOne = [[UIAlertView alloc] initWithTitle:nil message:REPORT_ONE_ALTERTION_ON delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [delegate.alertAutoOne show];
        [self performSelector:@selector(closeAlertViewOne) withObject:nil afterDelay:0];

    }else
    {
        [UIView animateWithDuration:0.3 animations:^{
            self.xbtn.constant = 0;
            self.backgroundImage.image = [UIImage imageNamed:@"sleep - background"];
            [self.view layoutIfNeeded];
        }];
        delegate.alertAutoOne = [[UIAlertView alloc] initWithTitle:nil message:REPORT_ONE_ALTERTION_OFF delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [delegate.alertAutoOne show];
        //0.8S隐藏
        [self performSelector:@selector(closeAlertViewOne) withObject:nil afterDelay:0];

    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    UserConfig * config = [UserConfig sharingUserConfig];
    delegate.sleepImprove = [config isSleepImprove];
    if (delegate.sleepImprove) {
        TJJLog(@"已经开启");
        self.xbtn.constant = self.slideView.frame.size.width/2;
        self.backgroundImage.image = [UIImage imageNamed:@"sleep - backgroundOn"];
        [self.view layoutIfNeeded];
    }else
    {
        self.xbtn.constant = 0;
        self.backgroundImage.image = [UIImage imageNamed:@"sleep - background"];
        [self.view layoutIfNeeded];
    }
    
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

#pragma mark -
#pragma mark 滑动改变睡眠
- (void)handleSwipes:(UISwipeGestureRecognizer *)sender
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        [UIView animateWithDuration:0.3 animations:^{
            self.xbtn.constant = 0;
            self.backgroundImage.image = [UIImage imageNamed:@"sleep - background"];
            [self.view layoutIfNeeded];
        }];
        
        //关闭睡眠
        Byte ACkValue[4] = {0};
        ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x16; ACkValue[3] = 0xAA;
        
        NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
            [self.myPeripheral writeValue:data
                        forCharacteristic:delegate.writeCharacteristic
                                     type:CBCharacteristicWriteWithResponse];
        }
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(sleepGaishan) userInfo:nil repeats:NO];
    }
    if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
        [UIView animateWithDuration:0.3 animations:^{
            self.xbtn.constant = self.slideView.frame.size.width/2;
            self.backgroundImage.image = [UIImage imageNamed:@"sleep - backgroundOn"];
            [self.view layoutIfNeeded];
        }];
        Byte ACkValue[4] = {0};
        ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x15; ACkValue[3] = 0xAA;
        NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
        if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
            [self.myPeripheral writeValue:data
                        forCharacteristic:delegate.writeCharacteristic
                                     type:CBCharacteristicWriteWithResponse];
        }
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(sleepGaishan) userInfo:nil repeats:NO];
    }
}

@end
